package admin

// by daoyi
//import "C"
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"log"
	"net/http"
	"simai_oa/controller"
	"simai_oa/model"
	"simai_oa/tool"
	"strconv"
)

var store = base64Captcha.DefaultMemStore

// 定义一个GoodController结构体
type LoginController struct {
	controller.BaseController // 继承BaseController
}

// Captcha
//
//	@Summary	后台生成验证码
//	@Tags		后台-登陆功能
//	@Success	200	{string}	json{"code","result"}
//	@Router		/admin/login/captcha [GET]
func Captcha(c *gin.Context) {
	//var store = base64Captcha.DefaultMemStore
	KeyLong := 4    //几位识别符号
	ImgHeight := 50 //图片高度 高度不能低于50
	ImgWidth := 170 //图片长度 长度不能低于170

	// 生成默认数字的driver
	driver := base64Captcha.NewDriverDigit(ImgHeight, ImgWidth, KeyLong, 0.7, 80)
	cp := base64Captcha.NewCaptcha(driver, store)
	if id, b64s, err := cp.Generate(); err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"code":   2,
			"result": "验证码获取失败",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    1,
			"result":  "验证码获取成功",
			"keyid":   id,
			"base64s": b64s,
		})
	}
}

// Index
//
//	@Summary	后台登陆页
//	@Tags		后台-登陆功能
//	@param		name	formData	string	false	"用户名"
//	@param		pwd		formData	string	false	"密码md5(密码+_KW)"
//	@param		keyid	formData	string	false	"验证码是对应key"
//	@param		base64s	formData	string	false	"验证码"
//	@Success	200		{string}	json{"code","message"}
//	@Router		/admin/login/index [POST]
func (con LoginController) Index(c *gin.Context) {

	//设置cookie
	controller.BaseController{}.Index(c)
	//获取cookie值
	//username,_ := c.Get("username")
	//fmt.Println(username)

	//获取get值
	name := c.DefaultPostForm("name", "0")
	//获取post值
	password := c.PostForm("pwd")
	CaptchaId := c.PostForm("keyid")
	CaptchaCode := c.PostForm("base64s")
	if CaptchaCode == "" || CaptchaId == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":   21,
			"result": "验证码缺失",
		})
		return
	}
	//password := c.DefaultPostForm("pwd","123456")
	//验证码验证
	errVerify := store.Verify(CaptchaId, CaptchaCode, true)
	if !errVerify {
		c.JSON(http.StatusOK, gin.H{
			"code":   2,
			"result": "验证码错误",
		})
		return
	}

	adminInfo := model.Admin{}
	//查询用户是否存在
	tool.Gdb.Where("name = ?", name).First(&adminInfo)

	if adminInfo.Switch == 2 {
		c.JSON(http.StatusOK, gin.H{
			"code":   2,
			"result": "账号不存在或已禁用，请联系管理员！",
		})
		return
	}

	kw := "_KW"
	pwd := tool.Md5string(password + kw)
	fmt.Println(pwd)
	//验证用户密码是否正确
	err := tool.PasswordVerify(pwd, adminInfo.Pwd, adminInfo.Salt)
	//err == nil 验证正确

	Id := uint(adminInfo.Id)

	if err == nil {
		// 使用jwt生成Token
		tokenString, errs := tool.GenToken(Id, adminInfo.Name, adminInfo.Type, adminInfo.GameId, adminInfo.RoleName)
		if errs != nil {
			log.Println(errs)
			c.JSON(http.StatusOK, gin.H{
				"code":     1001,
				"err_info": "生成token错误",
			})
			return
		}

		admin_log := model.AdminLogs{}
		types := []string{"登陆", "添加", "修改", "删除"}
		admin_log.CreatedAt = tool.GetDate()
		admin_log.UpdatedAt = tool.GetDate()
		admin_log.Type = 0
		admin_log.ActType = types[0]
		admin_log.RunUrl = c.Request.RequestURI
		admin_log.Username = name
		admin_log.Remark = "用户登录:" + name
		admin_log.UserIP = c.ClientIP()

		tool.Gdb.Create(&admin_log)

		adminInfo.Pwd = ""
		adminInfo.Salt = ""
		adminInfo.OpenId = ""

		c.JSON(http.StatusOK, gin.H{
			"code":   1,
			"result": adminInfo,
			"token":  tokenString,
		})
	} else {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"code":   2,
			"result": err,
		})
	}

	////设置session
	//session := sessions.Default(c)
	////设置session过期时间
	//session.Options(sessions.Options{
	//    MaxAge: 3600, //设置session过期时间
	//})
	//session.Set("sessionName","2131658715513251")
	//session.Save() //必须调用，ssession.save() 保存session值
	//
	//c.HTML(http.StatusOK, "admin/login.html", gin.H{
	//    "title": "首页sss" ,
	//})
}

// EditPwd
//
//	@Summary	用户修改密码
//	@Tags		后台-登陆功能
//	@param		old_password	query		string	false	"旧密码 + _KW"
//	@param		new_password	query		string	false	"新密码 + _KW"
//	@Success	200				{string}	json{"code","message"}
//	@Router		/admin/login/editpwd [POST]
func (User) EditPwd(c *gin.Context) {
	// 用户ID
	token, _ := tool.GetTokenFromRequest(c)
	uID := tool.GetValueFromTokenClaims("Id", token.Claims)
	userID, _ := strconv.Atoi(uID)
	reqData := make(map[string]string)
	err := c.Bind(&reqData)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	old_password := reqData["old_password"]
	new_password := reqData["new_password"]
	if len(new_password) < 6 || len(new_password) > 20 {
		controller.ResFail(c, "密码长度在 6 到 20 个字符")
		return
	}

	where := model.Admin{}
	where.Id = userID
	modelOld := model.Admin{}
	_, err = model.First(&where, &modelOld)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	old_password = tool.Md5string(old_password + modelOld.Salt)
	if old_password != modelOld.Pwd {
		controller.ResFail(c, "原密码输入不正确")
		return
	}
	new_password = tool.Md5string(new_password + modelOld.Salt)
	modelNew := model.Admin{Pwd: new_password}
	err = model.Updates(&modelOld, &modelNew)
	if err != nil {
		log.Println(err)
		controller.ResFail(c, "操作失败")
		return
	}
	controller.ResSuccessMsg(c)
}

// 用户登出
//func (User) Logout(c *gin.Context) {
//	t := c.GetHeader(controller.TOKEN_KEY)
//	if t == "" {
//		controller.ResFail(c, "操作失败")
//		return
//	}
//	u, ok := tool.JwtParseToken(t)
//	if !ok {
//		controller.ResFail(c, "操作失败")
//		return
//	}
//	cid := u["uuid"]
//	if cid == "" {
//		controller.ResFail(c, "操作失败")
//		return
//	}
//	cache.Del([]byte(cid))
//	controller.ResSuccessMsg(c)
//}
